from django.utils import timezone
from datetime import timedelta
from .models import MealPlan, DailyMeal, FoodItem
from .strategies import DietStrategyFactory


class DietPlanService:
    """饮食计划服务（上下文）"""

    def generate_meal_plan(self, user_profile, days=7):
        # 选择合适的策略
        strategy = DietStrategyFactory.get_strategy(user_profile)

        # 使用策略生成饮食计划
        plan_data = strategy.generate_diet_plan(user_profile, days)

        # 创建并保存饮食计划到数据库
        meal_plan = MealPlan.objects.create(
            user=user_profile,
            start_date=timezone.now().date(),
            end_date=timezone.now().date() + timedelta(days=days - 1),
            total_calories=plan_data['nutrient_goals']['calories'],
            strategy_used=plan_data['strategy_name']
        )

        # 创建每日饮食详情
        for daily_data in plan_data['daily_meals']:
            daily_meal = DailyMeal.objects.create(
                meal_plan=meal_plan,
                date=timezone.now().date() + timedelta(days=daily_data['day'] - 1)
            )

            # 添加早餐食物
            for food in daily_data['breakfast']:
                daily_meal.breakfast.add(food)

            # 添加午餐食物
            for food in daily_data['lunch']:
                daily_meal.lunch.add(food)

            # 添加晚餐食物
            for food in daily_data['dinner']:
                daily_meal.dinner.add(food)

            # 添加零食
            for food in daily_data['snacks']:
                daily_meal.snacks.add(food)

        return meal_plan